<?php
/**************************************************************************
	ESAM (EVE to SMF API Module)
	Copyright (C) 2009  Clinton Weiss

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/

if (!defined('SMF')) die('Hacking attempt...');

require_once 'EsamGlobal.php';
require_once 'EsamAlliance.php';
require_once 'EsamQuery.php';
require_once 'EsamSkillDump.php';

function EsamSettings()
{
	global $context, $txt, $scripturl;

	isAllowedTo(array('admin_forum'));

	adminIndex('EsamSettings');
	loadTemplate('EsamSettings');

  $context['page_title'] = $txt['eve_settings'];

	$context['admin_tabs'] = array(
		'title' => $txt['eve_settings'],
		'description' => 'add description here',
		'tabs' => array(
			'index' => array(
				'title' => $txt['eve_general_settings'],
				'description' => $txt['eve_general_settings'],
				'href' => $scripturl . '?action=EsamSettings;sa=index',
				'is_selected' => $_REQUEST['sa'] == 'index',
			),
			'rules' => array(
				'title' => $txt['eve_manage_rules'],
				'description' => $txt['eve_manage_rules'],
				'href' => $scripturl . '?action=EsamSettings;sa=rules',
				'is_selected' => $_REQUEST['sa'] == 'rules',
			),
			'validate' => array(
				'title' => 'Validate',
				'description' => 'Executes Validation against all known & valid API keys.',
				'href' => $scripturl . '?action=EsamSettings;sa=validate',
				'is_selected' => $_REQUEST['sa'] == 'validate',
        'is_last' => true,
			)
		)
	);

	$subActions = array(
		'index' => 'EsamSettingsIndex',
		'rules' => 'EsamRulesMenu',
		'validate' => 'EsamValidator',
		'delete_rule' => 'EsamDeleteRule',
	);
	$subActions[$_REQUEST['sa']]();
}

function saveGlobalSettingsCheckedValue($param_name, $setting_name)
{
	$valueSet =  isset($_REQUEST[$param_name]);

	$esamGlobal = new EsamGlobal();
	$esamGlobal->setGlobalSetting($setting_name, empty($valueSet) ? "false" : "true");
}

function EsamSettingsIndex()
{
	global $context, $txt;

	if(isset($_REQUEST["submit"]))
	{
		if(isset($_REQUEST["import_legacy"]))
		{
			importLegacyTables();
		}
		if(isset($_REQUEST["remove_legacy"]))
		{
			dropLegacyTables();
		}


		saveGlobalSettingsCheckedValue('api_required', "GLOBAL_REQUIRED_API");
		saveGlobalSettingsCheckedValue('display_eve_name', "DISPLAY_EVE_NAME");
		saveGlobalSettingsCheckedValue('add_corp_ticker', "ADD_CORP_TICKER");
		$context['extra_text'] = $txt['eve_settings_saved'];
	}
}

function importLegacyTables()
{
	$esamMember = new EsamMembers();
	$esamRules = new EsamRules();

	// First the api's
	$esamQuery = new EsamQuery();
	$esamQuery->setQuery("select * from {db_prefix}eve_api_keys");
	$apiList = $esamQuery->getResultSet();
	foreach ($apiList as $api)
	{
		$esamMember->saveEveUserData($api['ID_MEMBER'], $api['USER_ID'], $api['API_KEY']);
	}

	// then the rules
	$esamQuery->setQuery("select * from {db_prefix}eve_rules");
	$ruleList = $esamQuery->getResultSet();
	foreach ($ruleList as $rule)
	{
		$group_id = $rule['ID_GROUP'];
		$memberType = empty($rule['EVE_ROLE']) ? "member" : "roleDirector";
		if (!empty($rule['EVE_ALLIANCE_ID']))
		{
			// Alliance rule
			$esamRules->addRule("A", $memberType, $rule['EVE_ALLIANCE_ID'], $group_id);
		} else
		{
			// Corp rule
			$esamRules->addRule("C", $memberType, $rule['EVE_CORP_ID'], $group_id);
		}
	}
}

function dropLegacyTables()
{
	executeQuery("drop table {db_prefix}eve_api_keys");
	executeQuery("drop table {db_prefix}eve_alliances");
	executeQuery("drop table {db_prefix}eve_corporations");
	executeQuery("drop table {db_prefix}eve_rules");
	executeQuery("drop table {db_prefix}eve_characters");
	executeQuery("drop table {db_prefix}eve_settings");
}

function executeQuery($query)
{
	try {
		$esamQuery = new EsamQuery();
		$esamQuery->setQuery($query);
		$esamQuery->executeQuery();
	} catch (Exception $ex) {
		// oh well, table is gone already, move on
	}
}

function EsamDeleteRule()
{
	global $context;
	$context['sub_template'] = 'rules';
	$id_rule = $_REQUEST['rule_id'];
	if(isset($id_rule))
	{
		$esamRules = new EsamRules();
		$esamRules->deleteRule($id_rule);
	}
}

/**
 * Add rules
 *
 * @global <type> $context
 * @return <type>
 */
function EsamRulesMenu()
{
	global $context;
	$context['sub_template'] = 'rules';
	if(isset($_REQUEST["submit"]))
	{
		$esamRules = new EsamRules();

		$roleType = $_REQUEST["roleType"];
		$memberGroupId = $_REQUEST["memberGroupId"];
		$target = $_REQUEST["targetName"];
    $skillChecked = $_REQUEST["includeSkill"];
    $skillTypeId = $_REQUEST["skillTypeId"];
    $skillLvl = $_REQUEST["skillLvl"];

    if ($skillChecked != "skill")
    {
      $skillTypeId = "";
      $skillLvl = "";
    }
    
		if (!isset($target) || $target == null || $target == '')
		{
			return;
		}

		// is the target an alliance?
		$esamAlliance = new EsamAlliance();
		$allianceId = $esamAlliance->getAllianceId(mysql_escape_string($target));
		if (!empty($allianceId))
		{
			$esamRules->addRule("A", $roleType, $allianceId, $memberGroupId, $skillTypeId, $skillLvl);
		} else
		{
			// is the target a corporation?
			$eveapi = new EsamEveApi();
			$eveapi->setName($target);
			$content = $eveapi->getCharacterOrCorporationInfo();
			if ($eveapi->isError())
			{
				// echo $eveapi->getErrors();
				return;
			}
			$contentXml = new SimpleXMLElement($content);
			$targetId = (string) $contentXml->result->rowset->row['characterID'];

			if (!empty($targetId))
			{
				// We now have either a corp id or a character id
				$eveapi = new EsamEveApi();
				$eveapi->setCredentials(null, null, null, $targetId);
				$corpInfo = $eveapi->getCorporationInfo();
				if ($eveapi->isError())
				{
					// We have a pilot ID
					$esamRules->addRule("P", "pilot", (int) $targetId, $memberGroupId, $skillTypeId, $skillLvl);
				} else
				{
					$corpXml = new SimpleXMLElement($corpInfo);
					$corporationId = $corpXml->result->corporationID;
					if (((int) $corporationId) == ((int) $targetId))
					{
						// We have our corp
						$esamRules->addRule("C", $roleType, $corporationId, $memberGroupId, $skillTypeId, $skillLvl);
					}
				}
			}
			else
			{
				fatal_error("Cannot identify an Alliance, Corporation, or Pilot using the name " . $target , false);
			}
		}
	}
}

function EsamValidator()
{
	global $context;
	$context['sub_template'] = 'validator';
}
?>
